package com.grupit.engine.service.impl;

import java.io.IOException;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.log4j.Logger;

import com.grupit.engine.pluggablefeatures.domain.Note;
import com.grupit.engine.service.NoteService;

import es.chaveweb.poZit.server.domain.PMF;

public class JdoPoZit4GrupitServiceImpl implements NoteService {

	private static final Logger logger = Logger.getLogger(JdoPoZit4GrupitServiceImpl.class);

	@Override
	public Note findPoZitById(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			return pm.getObjectById(Note.class, id);
		} catch (JDOObjectNotFoundException e) {
			logger.warn(String.format("Nota no encontrada '%s' no encontrada", id)); //$NON-NLS-1$
			return null;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Note> findAllNotesByUserId(String userId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query q = pm.newQuery(Note.class);

			q.setFilter(String.format("ownerUserId==%d", userId));

			List<Note> list = (List<Note>) q.execute();
			return list;
		} finally {
			pm.close();
		}
	}

	@Override
	public void save(Note note) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			if (note.getId() == null) {
				pm.makePersistent(note);
			} else {
				Note read = pm.getObjectById(Note.class, note.getId());
				read.setNoteText(note.getNoteText());
				read.setX(note.getX());
				read.setY(note.getY());
			}
		} finally {
			pm.close();
		}
	}

	@Override
	public void delete(Note note) throws IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Note read = pm.getObjectById(Note.class, note.getId());
			pm.deletePersistent(read);
		} finally {
			pm.close();
		}
	}
}
